<template>
  <el-form ref="formRef" :model="_form" :rules="rules" label-width="80px" size="small">
    <el-form-item label="目录名称" prop="value">
      <el-input v-model.trim="_form.value" size="small" />
    </el-form-item>
    <el-form-item label="目录编码" prop="code">
      <el-input v-model.trim="_form.code" size="small" auto-complete="off" />
    </el-form-item>
    <el-form-item label="分类" prop="typeFk">
      <el-select v-model="_form.typeFk" size="small" clearable>
        <el-option v-for="item in clsOptions" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="启用" prop="status">
      <el-checkbox v-model="_form.status" :true-label="1" :false-label="0" />
    </el-form-item>
    <el-form-item label="锁定" prop="lockUp">
      <el-checkbox v-model="_form.lockUp" />
    </el-form-item>
    <remark v-model:remark="_form.remark" />
    <el-form-item>
      <drawer-footer :save-loading="state.saveLoading" @cancel="cancel" @confirm="confirm" />
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {
  computed,
  defineEmits,
  defineExpose,
  defineProps,
  PropType,
  reactive,
  ref,
  watch,
} from 'vue'

import { ElMessage } from 'element-plus'

import DrawerFooter from '&/components/DrawerFooter/index.vue'
import Remark from '&/components/Form/remark.vue'

import DictApi from '@/api/backend/dict'

import { commonTitleReg } from '@/utils/regExp'

import IBaseObj from '#/index'

const props = defineProps({
  form: {
    type: Object,
    default: () => {},
  },
  clsOptions: {
    type: Array as PropType<IBaseObj[]>,
    default: () => [],
  },
  isAdd: {
    type: Boolean,
    default: true,
  },
})

const emits = defineEmits(['update:form', 'cancel', 'confirm'])

const state = reactive({
  saveLoading: false,
  code: '',
})

const codeValidate = async (_rule: any, value: string, cb: Function) => {
  if (value) {
    if (!props.isAdd) {
      // 若是修改 并且字典目录没变 不需要校验
      if (state.code === value) {
        return cb()
      }
      const ret = await DictApi.checkExistCatalogCode(value)
      if (ret.data) {
        return cb(new Error('该目录编码已经存在！'))
      }
      return cb()
    }
    const ret = await DictApi.checkExistCatalogCode(value)
    if (ret.data) {
      return cb(new Error('该目录编码已经存在！'))
    }
    return cb()
  }
  return cb()
}

const rules = {
  value: [
    { required: true, message: '请输入目录名称', trigger: 'blur' },
    { ...commonTitleReg, trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入目录编码', trigger: 'blur' },
    { validator: codeValidate, trigger: 'blur' },
  ],
  typeFk: [{ required: true, message: '请选择分类', trigger: 'change' }],
}

watch(
  () => props.isAdd,
  (val) => {
    if (!val) {
      // 当修改的时候获取目录编码的值
      state.code = props.form.code
    }
  },
  {
    immediate: true,
  }
)
const _form: IBaseObj = computed({
  get() {
    return props.form
  },
  set(val) {
    emits('update:form', val)
  },
})

const cancel = () => {
  emits('cancel')
}

const formRef = ref()
const confirm = () => {
  formRef.value.validate(async (valid: Boolean) => {
    if (valid) {
      state.saveLoading = true
      try {
        let res = null
        let status = 0
        status = _form.value.status ? 1 : 0

        res = await DictApi.saveDictCatalog({ ..._form.value, status })

        const { status: statusCode } = res
        if (statusCode === 200) {
          if (props.isAdd) {
            ElMessage({ message: '创建成功!', type: 'success', duration: 1500 })
          } else {
            ElMessage({ message: '修改成功!', type: 'success', duration: 1500 })
          }
          emits('confirm')
        }
      } catch (error) {
        console.log(error)
      } finally {
        state.saveLoading = false
      }
    } else {
      return false
    }
  })
}

const clear = () => {
  formRef.value.resetFields()
  state.code = ''
}

defineExpose({
  clear,
})
</script>
